package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/finance")
public class FinanceController extends BaseController {

    @Reference
    private FinanceService financeService;
    @Reference
    private InvoiceService invoiceService;
    @Reference
    private ShippingOrderService shippingOrderService;
    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;
    @Reference
    private FactoryService factoryService;
    @Reference
    private ExportProductService exportProductService;


    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {

        FinanceExample financeExample = new FinanceExample();
        financeExample.createCriteria().andCompanyIdEqualTo(getLoginUserCompanyId());

        PageInfo<Finance> pageInfo = financeService.findByPage(financeExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);

        return "cargo/finance/finance-list";
    }


    @RequestMapping("/toAdd")
    public String toAdd(String invoiceId) {
        Invoice invoice = invoiceService.findById(invoiceId);

        //发票号
        request.setAttribute("invoiceId", invoiceId);

        //发票金额
        BigDecimal invoiceMoney = invoice.getInvoiceMoney();
        request.setAttribute("invoiceMoney", invoiceMoney);

        //发票时间
        Date invoiceTime = invoice.getInvoiceTime();
        request.setAttribute("invoiceTime", invoiceTime);

        //报运合同号
        String scNo = invoice.getScNo();
        request.setAttribute("scNo", scNo);

        //装运港
        ShippingOrder shippingOrder = shippingOrderService.findById(invoice.getShippingOrderId());
        String shipmentPort = shippingOrder.getPortOfLoading();
        request.setAttribute("shipmentPort", shipmentPort);
        //卸货港
        String destinationPort = shippingOrder.getPortOfDischar();
        request.setAttribute("destinationPort", destinationPort);

        //收货人
        Packing packing = packingService.findById(shippingOrder.getShippingOrderId());
        String exportIds = packing.getExportIds();
        String[] exportIdArr = exportIds.split(",");
        String exportId = exportIdArr[0];
        Export export = exportService.findById(exportId);

        request.setAttribute("consignee", export.getConsignee());

        return "cargo/finance/finance-add";

    }

    @RequestMapping("/edit")
    public String edit(Finance finance) {
        //补全数据
        finance.setCompanyId(getLoginUserCompanyId());
        finance.setCompanyName(getLoginUserCompanyName());
        finance.setCreateDept(getLoginUser().getDeptId());
        finance.setCreateBy(getLoginUser().getId());

        financeService.save(finance);

        //修改发票单的状态
        Invoice invoice = invoiceService.findById(finance.getInvoiceId());
        invoice.setState(1);
        invoiceService.update(invoice);

        return "redirect:/cargo/finance/list.do";
    }

    @RequestMapping("/toView")
    public String toView(String financeId) {
        Finance finance = financeService.findById(financeId);

        request.setAttribute("finance", finance);

        return "cargo/finance/finance-view";
    }


    @RequestMapping("/financeExcel")
    @ResponseBody
    public void financeExcel(String financeId) throws IOException {
        //1. 读取模板的输入流 , 读取webapp目录下的资源记得是使用ServletContext
        InputStream inputStream = session.getServletContext().getResourceAsStream("/make/xlsprint/tFINANCE.xls");
        //2.得到工作簿
        Workbook workbook = new HSSFWorkbook(inputStream);
        //3.得到工作单
        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(0);
        Cell cell = row.getCell(0);
        //表头部分
        //制单时间
        Integer totalCNumber =0;
        Integer totalBoxNum = 0;
        Double totalGW = 0.0;
        Double totalNW = 0.0;
        Double totalSize = 0.0;
        Double totalExAm = 0.0;
        Double totalAm = 0.0;
        Double totalTax = 0.0;
        Finance finance = financeService.findById(financeId);
        Date inputDate = finance.getInputDate();
        if (inputDate != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String inputTime = simpleDateFormat.format(inputDate);
            row = sheet.getRow(1);
            cell = row.getCell(3);
            cell.setCellValue(inputTime);
        }
        row = sheet.getRow(1);
        //发票号
        cell = row.getCell(15);
        cell.setCellValue(finance.getInvoiceId());
        //合同号
        row = sheet.getRow(2);
        cell = row.getCell(4);
        cell.setCellValue(finance.getExportNos());
        //信用号
        cell = row.getCell(13);
        Invoice invoice = invoiceService.findById(finance.getInvoiceId());
        ShippingOrder shippingOrder = shippingOrderService.findById(invoice.getShippingOrderId());
        cell.setCellValue(shippingOrder.getLcNo());
        //收货人地址
        row = sheet.getRow(3);
        cell = row.getCell(4);
        cell.setCellValue(finance.getConsigenn());
        //备注

        //装运港
        row = sheet.getRow(4);
        cell = row.getCell(2);
        cell.setCellValue(finance.getShipmentPort());
        //目的港
        cell = row.getCell(5);
        cell.setCellValue(finance.getDestinationPort());

        //价格条件
        cell = row.getCell(10);
        cell.setCellValue(invoice.getTradeTerms());
        row = sheet.getRow(7);
        cell = row.getCell(1);
        CellStyle[] cellStyles = new CellStyle[15];
        cellStyles[0] = cell.getCellStyle();
        for (int i = 1; i < cellStyles.length; i++) {
            cell = row.getCell(i + 3);
            cellStyles[i] = cell.getCellStyle();
        }

        int index = 6;

        //拿到报运单的所有货物
        Packing packing = packingService.findById(shippingOrder.getShippingOrderId());
        String[] exportIds = packing.getExportIds().split(",");
        for (int i = 0; i < exportIds.length; i++) {
            String exportId = exportIds[i];

            Export export = exportService.findById(exportId);
            ExportProductExample exportProductExample = new ExportProductExample();
            exportProductExample.createCriteria().andExportIdEqualTo(exportId);
            List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);

            for (ExportProduct exportProduct : exportProductList) {
                index++;
                row = sheet.createRow(index);
                //货号
                String productNo = exportProduct.getProductNo();
                    cell = row.createCell(1);
                    cell.setCellStyle(cellStyles[0]);
                if (productNo != null) {
                    cell.setCellValue(productNo);
                }
                //厂家
                String factoryId = exportProduct.getFactoryId();
                Factory factory = factoryService.findById(factoryId);
                String factoryName = factory.getFactoryName();
                cell = row.createCell(4);
                    cell.setCellStyle(cellStyles[1]);
                if (factoryName != null) {
                    cell.setCellValue(factoryName);
                }
                //单位
                String packingUnit = exportProduct.getPackingUnit();
                    cell = row.createCell(5);
                    cell.setCellStyle(cellStyles[2]);
                if (packingUnit != null) {
                    cell.setCellValue(packingUnit);
                }
                //数量
                Integer cnumber = exportProduct.getCnumber();
                    cell = row.createCell(6);
                    cell.setCellStyle(cellStyles[3]);
                if (cnumber != null) {
                    cell.setCellValue(cnumber);
                    totalCNumber+=cnumber;
                }
                //件数
                Integer boxNum = exportProduct.getBoxNum();
                    cell = row.createCell(7);
                    cell.setCellStyle(cellStyles[4]);
                if (boxNum != null) {
                    cell.setCellValue(boxNum);
                    totalBoxNum+=boxNum;
                }
                //毛重
                Double grossWeight = exportProduct.getGrossWeight();
                    cell = row.createCell(8);
                    cell.setCellStyle(cellStyles[5]);
                if (grossWeight != null) {
                    cell.setCellValue(grossWeight);
                    totalGW+=grossWeight;
                }
                //净重
                Double netWeight = exportProduct.getNetWeight();
                    cell = row.createCell(9);
                    cell.setCellStyle(cellStyles[6]);
                if (netWeight != null) {
                    cell.setCellValue(netWeight);
                    totalNW+=netWeight;
                }
                //长
                Double sizeLength = exportProduct.getSizeLength();
                    cell = row.createCell(10);
                    cell.setCellStyle(cellStyles[7]);
                if (sizeLength != null) {
                    cell.setCellValue(sizeLength);
                }
                //宽
                Double sizeWidth = exportProduct.getSizeWidth();
                    cell = row.createCell(11);
                    cell.setCellStyle(cellStyles[8]);
                if (sizeWidth != null) {
                    cell.setCellValue(sizeWidth);
                }
                //高
                Double height = exportProduct.getSizeHeight();
                    cell = row.createCell(12);
                    cell.setCellStyle(cellStyles[9]);
                if (height != null) {
                    cell.setCellValue(height);
                }

                if(sizeLength!=null&&height!=null&&sizeWidth!=null&&cnumber!=null){
                   Double size = sizeLength*height*sizeWidth*cnumber/1000000;

                   totalSize+=size;
                }

                //出口单价
                Double exPrice = exportProduct.getExPrice();
                    cell = row.createCell(13);
                    cell.setCellStyle(cellStyles[10]);
                if (exPrice != null) {
                    cell.setCellValue(exPrice);
                }
                //出口金额
                    cell = row.createCell(14);
                    cell.setCellStyle(cellStyles[11]);
                if (exPrice != null && cnumber != null) {
                    Double exAmount = exPrice * cnumber;
                    cell.setCellValue(exAmount);
                    totalExAm+=exAmount;
                }
                //合同单价
                Double price = exportProduct.getPrice();
                    cell = row.createCell(15);
                    cell.setCellStyle(cellStyles[12]);
                if (price != null) {
                    cell.setCellValue(price);
                }
                //税收
                Double tax = exportProduct.getTax();
                    cell = row.createCell(17);
                    cell.setCellStyle(cellStyles[14]);
                if (tax != null) {
                    cell.setCellValue(tax);
                    totalTax+=tax;
                }
                //合同货物总价
                    cell = row.createCell(16);
                    cell.setCellStyle(cellStyles[13]);
                if (tax != null && cnumber != null && price != null) {
                    Double amount = (cnumber * price) - tax;
                    cell.setCellValue(amount);
                    totalAm+=amount;
                }
            }

        }

        index = index + 1;

        sheet.addMergedRegion(new CellRangeAddress(index,index,10,12));
        row = sheet.getRow(index);
        cell = row.createCell(1);
        cell.setCellValue("合计");
        cell.setCellStyle(cellStyles[0]);

        cell = row.createCell(4);
        cell.setCellStyle(cellStyles[1]);

        cell = row.createCell(5);
        cell.setCellStyle(cellStyles[2]);

        cell = row.createCell(13);
        cell.setCellStyle(cellStyles[10]);

        cell = row.createCell(15);
        cell.setCellStyle(cellStyles[12]);

        cell = row.createCell(6);
        cell.setCellStyle(cellStyles[3]);
        cell.setCellValue(totalCNumber);

        cell = row.createCell(7);
        cell.setCellStyle(cellStyles[4]);
        cell.setCellValue(totalBoxNum);

        cell = row.createCell(8);
        cell.setCellStyle(cellStyles[5]);
        cell.setCellValue(totalGW);

        cell = row.createCell(9);
        cell.setCellStyle(cellStyles[6]);
        cell.setCellValue(totalNW);


        cell = row.createCell(10);
        cell.setCellStyle(cellStyles[7]);
        cell.setCellValue(totalSize);

        cell = row.createCell(14);
        cell.setCellStyle(cellStyles[9]);
        cell.setCellValue(totalExAm);

        cell = row.createCell(16);
        cell.setCellStyle(cellStyles[11]);
        cell.setCellValue(totalAm);

        cell = row.createCell(17);
        cell.setCellStyle(cellStyles[14]);
        cell.setCellValue(totalTax);


        //字节数组输出流，该类的本质就是内部维护一个字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //把工作簿数据写入到ByteArrayOutputStream中
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream,response,"出口商品报运单.xls");


    }

}
